import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:share_fit/app/components/back_btn_icon.dart';
import 'package:share_fit/app/controllers/main/login/login_logic.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/tools/color_const.dart';
import 'package:share_fit/generated/locales.g.dart';

class SMSLoginPage extends StatelessWidget {

  final logic = Get.put(LoginLogic());
  final FocusNode _focusNodeName = FocusNode();
  final FocusNode _focusNodePwd = FocusNode();
  String nameValue = '';
  String pwdValue = '';

  late Timer timer;
  int _timeCount = 60;
  bool isDownTimer = false;

  @override
  Widget build(BuildContext context) {
    logic.setNameFocus(false);
    logic.setPwdFocus(false);
    logic.setCodeText(LocaleKeys.login_obtain_code.ts);
    _focusNodeName.addListener(() {
      logic.setNameFocus(_focusNodeName.hasFocus);
    });
    _focusNodePwd.addListener(() {
      logic.setPwdFocus(_focusNodePwd.hasFocus);
    });

    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        centerTitle: true,
        leading: BackBtnIcon(onTap: () {
          Get.offNamed('/login', arguments: {'isFromSpace': false});
        }),
      ),
      body: Container(
        padding: EdgeInsets.only(top: 168.h),
        child: Column(
          children: [
            Text(LocaleKeys.login_code.ts, style: TextStyle(fontSize: 70.sp, color: Color(0xFF222222))),
            _getUsernameInput(),
            _getPasswordInput(),
            Container(
              height: 136.h,
              width: 1.sw,
              margin: EdgeInsets.fromLTRB(42.w, 203.h, 42.w, 0),
              child: ElevatedButton(
                onPressed: () {
                  if(nameValue.isEmpty||pwdValue.isEmpty) {
                    logic.showTips('', LocaleKeys.login_phone_code_error.ts);
                    // showToastWidget(
                    //     Container(
                    //       width: 1.sw,
                    //       height: 260.h,
                    //       margin: EdgeInsets.only(left: 182.w, right: 182.w),
                    //       decoration: BoxDecoration(
                    //           color: Colors.white,
                    //           borderRadius: BorderRadius.circular(10)
                    //       ),
                    //       alignment: Alignment.center,
                    //       child: Text(LocaleKeys.login_phone_code_error.ts, style: TextStyle(color: ColorConst.primaryFontColor, fontSize: 54.sp),),
                    //     ),
                    //     context: context,
                    //     position: StyledToastPosition.center,
                    //     animation: StyledToastAnimation.scale,
                    //     reverseAnimation: StyledToastAnimation.fade,
                    //     duration: Duration(seconds: 3),
                    //     animDuration: Duration(seconds: 1),
                    //     curve: Curves.elasticOut,
                    //     reverseCurve: Curves.linear);
                    return;
                  }
                  logic.save('login_state', true, global: true);
                  Get.offAllNamed('/main');
                },
                style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.all(ColorConst.activeColor),
                    shape: MaterialStateProperty.all(RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10)
                    ))
                ),
                child: Text(LocaleKeys.login.ts, style: TextStyle(fontSize: 48.sp, color: Colors.white, ),),
              ),),
          ],
        ),
      )
    );
  }

  Widget _getUsernameInput(){
    return GetBuilder<LoginLogic>(
        id: 'login_name_focus',
        builder: (_){
          return Container(
            margin: EdgeInsets.fromLTRB(42.w, 200.h, 42.w, 0),
            child: Column(
              children: [
                TextField(
                  maxLines: 1,
                  focusNode: _focusNodeName,
                  cursorColor: ColorConst.secondaryFontColor,
                  onChanged: (value) {
                    nameValue = value;
                  },
                  decoration: InputDecoration(
                    icon: Container(
                      alignment: Alignment.bottomCenter,
                      width: 60.w,
                      child: ColorFiltered(
                        colorFilter:ColorFilter.mode(logic.state.isFocusedName?ColorConst.accentColor:ColorConst.secondaryFontColor, BlendMode.srcATop),
                        child: Image.asset('assets/images/space/icon_login_name.png', width: 60.w, height: 60.w,),
                      ),
                      // child: Image.asset('assets/images/space/icon_login_name.png', width: 60.w, height: 60.w,),
                    ),
                    hintText: LocaleKeys.login_input_phone_email.ts,
                    hintStyle: TextStyle(color: logic.state.isFocusedName?ColorConst.accentColor:ColorConst.secondaryFontColor, fontSize: 42.sp),
                    border: InputBorder.none,
                  ),
                ),
                Divider(height: 1.h,)
              ],
            ),
          );
        });
  }

  Widget _getPasswordInput(){
    return GetBuilder<LoginLogic>(
        id: 'login_pwd_focus',
        builder: (_){
          return Container(
            margin: EdgeInsets.fromLTRB(42.w, 72.h, 42.w, 0),
            child: Column(
              children: [
                Row(children: [
                  Container(
                    width: 0.7.sw,
                    child: TextField(
                      maxLines: 1,
                      focusNode: _focusNodePwd,
                      // enableInteractiveSelection: false,
                      obscureText: logic.state.obscureText,
                      cursorColor: ColorConst.secondaryFontColor,
                      onChanged: (value) {
                        pwdValue = value;
                      },
                      decoration: InputDecoration(
                          icon: Container(
                            alignment: Alignment.bottomCenter,
                            width: 60.w,
                            child: ColorFiltered(
                              colorFilter:ColorFilter.mode(logic.state.isFocusedPwd?ColorConst.accentColor:ColorConst.secondaryFontColor, BlendMode.srcATop),
                              child: Image.asset('assets/images/space/icon_login_pwd.png', width: 60.w, height: 60.w,),
                            ),
                          ),
                          hintText: LocaleKeys.login_input_code.ts,
                          hintStyle: TextStyle(color: logic.state.isFocusedPwd?ColorConst.accentColor:ColorConst.secondaryFontColor, fontSize: 42.sp),
                          border: InputBorder.none
                      ),
                    ),
                  ),
                  GestureDetector(
                    onTap: (){
                      if(!isDownTimer) {
                        startTimer();
                      }
                    },
                    child: Container(
                      width: 250.w,
                      height: 100.h,
                      padding: EdgeInsets.only(bottom: 10.h),
                      alignment: Alignment.bottomRight,
                      child: GetBuilder<LoginLogic>(
                        id: 'sms_code_text',
                        builder: (_){
                          return Text(logic.state.codeText, style: TextStyle(fontSize: 42.sp, color: ColorConst.accentColor),);
                        },
                      ),
                    ),
                  ),
                ],),
                Divider(height: 1.h,)
              ],
            ),
          );
        });
  }

  void startTimer() {
    timer = Timer.periodic(const Duration(seconds: 1), (Timer timer) {
      if(_timeCount<=0) {
        isDownTimer = false;
        _timeCount = 60;
        timer.cancel();
        logic.setCodeText(LocaleKeys.login_obtain_code.ts);
      } else {
        isDownTimer = true;
        logic.setCodeText('$_timeCount ${LocaleKeys.time_unit_second.ts}');
        _timeCount -= 1;
      }
    });
  }
}